<?php

require_once 'Zend/Controller/Plugin/Abstract.php';
require_once 'SubfolderAccessManager/Acl.php';

class SubfolderAccessManager_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
	protected $_auth;
	protected $_acl;
	protected $_action;
	protected $_controller;
	protected $_currentRole;

	/**
	 * Constructor
	 *
	 * Optionally set view object and options.
	 *
	 * @param  Zend_View_Interface $view
	 * @param  array $options
	 * @return void
	 */
	public function __construct()
	{
		$this->_auth = Zend_Auth::getInstance();
		$this->_acl = new SubfolderAccessManager_Acl();
	}

	protected function _init($request) {
		$this->_action = $request->getActionName();
		$this->_controller = $request->getControllerName();
		$this->_currentRole = $this->_getCurrentUserRole();
	}

	public function preDispatch(Zend_Controller_Request_Abstract $request) {

		$this->_init($request);

		// if the current user role is not allowed to do something
		if (!$this->_acl->isAllowed($this->_currentRole, $this->_controller, $this->_action)) {

			if (!$this->_auth->hasIdentity()) {
				$noPermsAction = $this->_acl->getNoAuthAction();
			} else {
				$noPermsAction = $this->_acl->getNoAclAction();
			}
			$request->setModuleName($noPermsAction['module']);
			$request->setControllerName($noPermsAction['controller']);
			$request->setActionName($noPermsAction['action']);
		}
	}

	protected function _getCurrentUserRole() {

		if ($this->_auth->hasIdentity()) {
			$authData = $this->_auth->getIdentity();
			$role = isset($authData->role)? strtolower($authData->role): 'guest';
		} else {
			$role = 'guest';
		}

		return $role;
	}
}
